package cn.com.shiro;


import cn.com.Model.User;
import cn.com.Service.UserService;


import lombok.extern.log4j.Log4j;


import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;

import org.apache.shiro.cache.CacheManager;
import org.apache.shiro.cache.ehcache.EhCacheManager;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.stereotype.Component;


import javax.annotation.Resource;

/**
 * Created by luokun on 2018/3/15.
 */
@Log4j
@Component
public class CustomRealm extends AuthorizingRealm {

    @Resource
    private UserService userService;



    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals)
    {

        return null;

    }


    /**
     * 登录验证
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken )
            throws AuthenticationException {
        //基于用户名和密码的令牌
        //这个令牌是从registController的currentUser.login(token)传来的
        UsernamePasswordToken token = (UsernamePasswordToken)authcToken;
        //调用service通过用户账户查询用户
        User userAuth = userService.getUserAuthByAccount(token.getUsername());
        if (userAuth == null) {
            // 抛出 帐号找不到异常
            throw new UnknownAccountException();
        }
        String identity = userAuth.getName();
        String password = userAuth.getPassword();

            AuthenticationInfo   authInfo = new SimpleAuthenticationInfo(userAuth
                    , password, ByteSource.Util.bytes(identity), this.getName());
         log.info("登陆认证结束！");
        return authInfo;

    }


}
